package controllers

import (
	"gitee.com/johng/gf/g/frame/gmvc"
	"gitee.com/johng/gf/g/os/gfile"
	"math/rand"
	"time"
	"gitee.com/johng/gf/g/net/ghttp"
	"strconv"
)

type ControllerUpload struct {
	gmvc.Controller
}

var uploadhtml = `
	<html>
    <head>
        <title>上传文件</title>
    </head>
        <body>
            <form enctype="multipart/form-data" action="/file/upload" method="post">
                <input type="file" name="upload-file" /></br>
                <input type="submit" value="upload" />
            </form>
        </body>
    </html>
	`

func init() {
	rand.Seed(time.Now().UnixNano())
	/*
	测试初始化随机树
	a := rand.Uint64() -> 1354805381297061470
	fmt.Println(a)
	b := rand.Int63n(36)
	fmt.Println(b) - > 27
	*/
	ghttp.GetServer().BindController("/file", &ControllerUpload{})
}
func (c *ControllerUpload) Index() {
	//``多行文本字符串定义
	c.Response.Write(uploadhtml)
}

func (c *ControllerUpload) Upload() {
	if file, fileheader, error := c.Request.FormFile("upload-file"); error == nil {
		defer file.Close()
		randomfilename := strconv.FormatUint(rand.Uint64(), 36)
		name := randomfilename + gfile.Basename(fileheader.Filename)
		fbuffer := make([]byte, fileheader.Size)
		//file读成二进制流
		file.Read(fbuffer)
		//gf上传文件 二进制处理
		uploadpath := "d://" + name
		gfile.PutBinContents(uploadpath, fbuffer)
		//c.Response.Write(`alert("upload successly.")`)
		c.Response.Write("upload successly." + uploadpath)

		//c.Response.RedirectTo("/file")
	} else {
		c.Response.Write("upload error:", error.Error())
	}

}
